package com.james.codeauto.web;

import com.james.codeauto.tools.json.JSONObject;
import com.james.codeauto.util.MD5;

import java.util.HashMap;
import java.util.Map;

public class TransApi {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private static String appid = "20220509001208711";
    private static String securityKey = "WUjhoGeIhV0Y28RpfccZ";

    public TransApi() {

    }

    public static String getTransResultDtoName(String query) {
//        if (true) {
//            return "TestDto";
//        }
        if(query.indexOf("(")>-1){
            query =query.substring(0,query.indexOf("("));
        }
        if(query.indexOf("（")>-1){
            query =query.substring(0,query.indexOf("（"));
        }
        if(query.indexOf("、")>-1){
            query =query.substring(query.lastIndexOf("、")+1,query.length());
        }
        if(query.indexOf(":")>-1){
            query =query.substring(0,query.indexOf(":"));
        }
        if(query.indexOf("：")>-1){
            query =query.substring(0,query.indexOf("："));
        }
        query= query.replaceAll("/","");
        query = query.replaceAll("\\[" , "").replaceAll("]" , "").replaceAll("查询" , "").replaceAll("获取" , "").replaceAll("信息" , "").replaceAll("\\(" , "").replaceAll("\\)" , "").replaceAll("（" , "").replaceAll("）" , "").replaceAll("]" , "").replaceAll("-" , "").replaceAll("\\[" , "");
        String from = "auto";
        String to = "en";
        JSONObject params = buildParams(query, from, to);
        JSONObject html = HttpClient.doPostForJson(TRANS_API_HOST, params, true);
        System.out.println("html==" + html.toString());
        String keyDto = html.optJSONArray("trans_result").getJSONObject(0).getString("dst");
        //  keyDto = keyDto.replace("listOf","");
        //  keyDto = keyDto.replace("ListOf","");
        String key = "";
        String[] words = keyDto.split(" ");
        for (int i = 0; i < words.length; i++) {
            key += words[i].substring(0, 1).toUpperCase() + words[i].substring(1);
        }
        key = key.replace("ListOf" , "").replace("-" , "");
        key = key.replace("Don't","Not");
        key = key.replace(",","With");

        key += "Dto";
        return key;
    }

    private static JSONObject buildParams(String query, String from, String to) {
        JSONObject params = new JSONObject();
        params.put("q" , query);
        params.put("from" , from);
        params.put("to" , to);

        params.put("appid" , appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt" , salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign" , MD5.md5(src));

        return params;
    }

}
